﻿/// <reference path="jquery-1.5.1-vsdoc.js" />

////////////////////// ////////// HGO TextBox Start Code ///////////////////////////////////
/////  This Code Copy and Paste From Telerik Numeric TextBox Source Code And Modified //////
////////////////////////////////////////////////////////////////////////////////////////////

(function ($) {

  var $t = $.telerik,
        keycodes = [8, // backspace
                    9, // tab
                    37, // left arrow
                    38, // up arrow
                    39, // right arrow
                    40, // down arrow
                    46, // delete
                    35, // end
                    36, // home
                    44], //","
        styles = ["font-family",
                  "font-size",
                  "font-stretch",
                  "font-style",
                  "font-weight",
                  "line-height",
                  "color",
                  "text-align",
                  "text-decoration",
                  "text-transform"];

  function getStyles(input) {
    var retrievedStyles = {};
    for (var i = 0, length = styles.length; i < length; i++) {
      var style = styles[i],
                value = input.css(style);

      if (value) {
        if (styles[i] != "font-style" && value != "normal") {
          retrievedStyles[style] = value;
        }
      }
    }

    return retrievedStyles;
  }

  $t.hgotextbox = function (element, options) {
    if (element.nodeName.toLowerCase() !== "input" && element.type.toLowerCase() !== "text") {
      throw "Target element is not a INPUT";
    }

    $.extend(this, options);

    this.element = element;
    var $element = this.$element = $(element)
            .bind({
              keydown: $.proxy(this._keydown, this),
              keypress: $.proxy(this._keypress, this)
            })
            .bind("paste", $.proxy(this._paste, this));

    $element.closest("form").bind("reset", $.proxy(this._onParentFormReset, this));

    var builder = new $t.stringBuilder();

    if (element.parentNode.nodeName.toLowerCase() !== "div") {
      $element.addClass('t-input').wrap($('<div class="t-widget t-hgotextbox"></div>'));
    }

    if ((element.nextSibling == null) || (element.nextSibling.nodeName.toLowerCase() !== "a")) {
      builder.buffer = [];

      if (this.showTextDeleteButton) {
        builder.cat('<a class="t-link t-icon t-hgodeletebutton" href="#" tabindex="-1" ');
        builder.cat('title="' + this.textDeleteButtonTitle + '"')
        builder.cat('">DeleteText</a>');

        if (builder.buffer.length > 0) {
          $(builder.string()).insertAfter($element);
        }
      }
    }

    this.$wrapper = $element.closest('.t-hgotextbox')
            .find('.t-hgodeletebutton')
                .bind({
                  click: $t.preventDefault,
                  dragstart: $t.preventDefault
                })
            .end()
            .bind({
              focusin: $.proxy(this._focus, this),
              focusout: $.proxy(this._blur, this)
            });

    // Eğer 16 pixel'den küçük ise yükseklik 16 pixele çekiliyor.
    // IE'DE bozulma nedeni icon'un büyüklüğü...
    var heighttmp = element.offsetHeight;
    if (heighttmp < 16)
      element.style.height = heighttmp + "px";

    this.enabled = !$element.is('[disabled]');

    // Background-Image enable ise set ediliyor.
    this.$wrapper.css('background-image', this.backgroundImage);
    this.$wrapper.css('background-color', '#EAEAEA');

    //    builder.buffer = [];
    //    builder.cat('[ |')
    //               .cat(this.groupSeparator)
    //               .catIf('|' + this.symbol, this.symbol)
    //               .cat(']');
    //    this.replaceRegExp = new RegExp(builder.string(), 'g');

    var inputValue = $element.attr('value'),
            cssClass = $element.attr('class').replace("t-input", "");

    //    builder.buffer = [];
    //    builder.cat('<div class="t-hgotextbox-formatted-value')
    //               .catIf(' t-state-empty', inputValue == '' && this.enabled)
    //               .catIf(cssClass, cssClass)
    //               .cat('">')
    //               .cat(inputValue || (this.enabled ? this.text : ''))
    //               .cat('</div>');

    //    this.$text = $(builder.string())
    //                        .insertBefore($element)
    //                        .css(getStyles($element))
    //                        .click(function (e) {
    //                          element.focus();
    //                        });

    //set text color to the background-color
    this._blur();
    this[this.enabled ? 'enable' : 'disable']();

    //this.val = this.parse(this.val);
    this.value(inputValue);

    var wrapperWidth = this.$wrapper.width();
    this.$wrapper.css('width', wrapperWidth);

    element.style.width = this.showTextDeleteButton ? ((wrapperWidth - 24) + "px") : ((wrapperWidth - 4) + "px");

    // IE değil ise...
    var wrapperheight = this.$wrapper.height();
    if (!PageMethods.isIE) {
      element.style.height = ((wrapperheight - 5) + "px");
    }
    else {
      element.style.height = ((wrapperheight - 3) + "px");
    }

    if (PageMethods.isIE) {
      element.style.lineHeight = ((wrapperheight - 3) + "px");
    }

    var $button = this.$wrapper.find('.t-hgodeletebutton');
    if ((this.showTextDeleteButton) && (inputValue != '')) {
      $button.show();
    }
    else {
      $button.hide();
    };

    $t.bind(this, {
      load: this.onLoad,
      valueChange: this.onChange
    });
  }

  $t.hgotextbox.prototype =
  {
    _paste: function (e) {
      setTimeout($.proxy(function () {

        var val = e.target.value;
        this._update(val);

      }, this));
    },

    _keydown: function (e) {

      //      setTimeout($.proxy(function () {
      //        $element.toggleClass('t-state-error', !this.inRange(this.parse($element.val()), this.minValue, this.maxValue));
      //      }, this));

      //      var key = e.keyCode,
      //                $element = this.$element,
      //                element = $element[0],
      //                value = $element.val(),
      //                separator = this.separator,
      //                selection = currentSelection(element),
      //                start = selection.start,
      //                end = selection.end,
      //                separatorIndex = value ? value.indexOf(separator) : -1,
      //                allowSeparator = separatorIndex === -1;

      //      if (!allowSeparator && start !== -1) {
      //        if (separatorIndex >= start && separatorIndex < end) {
      //          allowSeparator = true;
      //        }
      //      }

      //      var specialDecimals = this.specialDecimals[key];
      //      if (specialDecimals) {
      //        if (allowSeparator) {
      //          var firstSliceEnd,
      //                        secondSliceStart;

      //          if (start != -1) {
      //            firstSliceEnd = start;
      //            secondSliceStart = end;
      //          } else {
      //            var caret = $t.caretPos(element);
      //            firstSliceEnd = caret;
      //            secondSliceStart = caret;
      //          }
      //          $element.val(value.slice(0, firstSliceEnd) + specialDecimals + value.slice(secondSliceStart, value.length));
      //          if ($.browser.msie) {
      //            if (element.createTextRange) {
      //              var range = element.createTextRange();
      //              range.moveStart('textedit', 1);
      //              range.select();
      //            }
      //          }
      //        }
      //        return false;
      //      }

      //      Allow decimal
      //      var decimalSeparator = this.decimals[key];
      //      if (decimalSeparator) {
      //        if (decimalSeparator === separator && this.digits > 0 && allowSeparator) {
      //          return true;
      //        } else {
      //          e.preventDefault();
      //        }
      //      }

      //      if (key == 8 || key == 46 || key == 13) { //backspace and delete
      //        setTimeout($.proxy(function () {
      //          this._update(this.parse($element.val()));
      //        }, this));
      //        return true;
      //      }

      //      if (key == 38 || key == 40) {
      //        var direction = key == 38 ? 1 : -1;
      //        this._modify(direction * this.step);
      //        return true;
      //      }

      //      if (key == 222) e.preventDefault();

      return true;
    },

    _keypress: function (e) {
      //      var element = e.target,
      //                key = e.keyCode || e.which;

      //      if (key == 0 || $.inArray(key, keycodes) != -1 || e.ctrlKey || (e.shiftKey && key == 45)) {
      //        return true;
      //      }

      //      var isSignAllowed;
      //      if (this.minValue !== null && this.minValue < 0) {
      //        if (currentSelection(element).start === 0
      //                || ($t.caretPos(element) === 0 && element.value.indexOf("-") === -1)) {
      //          isSignAllowed = true;
      //        }
      //      }

      //      if ((isSignAllowed && String.fromCharCode(key) == "-") || this.inRange(key, 48, 57)) {
      //        return true;
      //      }

      return true;
    },

    _focus: function () {
      if (this.enabled) {
        var input = this.$element[0];
        setTimeout(function () {
          input.focus();
        }, 0);
      }
    },

    focus: function () {
      this._focus();
    },

    hide: function () {
      var wrapper = this.$wrapper;
      wrapper.hide();
    },

    show: function () {
      var wrapper = this.$wrapper;
      wrapper.show();
    },

    _blur: function () {
      // this.$element.removeClass('t-state-error');

      //if (this.enabled) {
      //this.$text.show();
      //this._hideTextBoxValue();
      //}

      //      var min = this.minValue,
      //                max = this.maxValue,
      //                parsedValue = this.parse(this.$element.val());

      //      if (parsedValue != null) {
      //        if (min != null && parsedValue < min) {
      //          parsedValue = min;
      //        } else if (max != null && parsedValue > max) {
      //          parsedValue = max;
      //        }
      //        parsedValue = parseFloat(parsedValue.toFixed(this.digits));
      //      }

      // Input elementinin değeri ile güncelleme yapılır.
      this._update(this.$element.val());

    },

    _clearTimer: function (e) {
      clearTimeout(this.timeout);
      clearInterval(this.timer);
      clearInterval(this.acceleration);
    },

    //    _stepper: function (e, stepMod) 
    //    {
    //      if (e.which == 1) 
    //      {
    //        var step = this.step;

    //        this._modify(stepMod * step);

    //        this.timeout = setTimeout($.proxy(function () {
    //          this.timer = setInterval($.proxy(function () {
    //            this._modify(stepMod * step);
    //          }, this), 80);

    //          this.acceleration = setInterval(function () { step += 1; }, 1000);
    //        }, this), 200);
    //      }
    //    },

    _modify: function (step) {
      //      var value = this.parse(this.element.value),
      //                min = this.minValue,
      //                max = this.maxValue;

      //      value = value ? value + step : step;

      //      if (min !== null && value < min) {
      //        value = min;
      //      } else if (max !== null && value > max) {
      //        value = max;
      //      }

      // this._update(parseFloat(value.toFixed(this.digits)));

      this._update(this.$element.val());
    },

    _update: function (val) {
      var oldValue = this.val;
      this._value(val);

      if (oldValue != val) {
        if ($t.trigger(this.element, 'valueChange', { oldValue: oldValue, newValue: val })) {
          this._value(oldValue);
        }
      }

      var $button = this.$wrapper.find('.t-hgodeletebutton');
      if ((this.showTextDeleteButton) && (val != '')) {
        $button.css("display", "block");
      }
      else {
        $button.css("display", "none");
      }

    },

    _value: function (value) {
      var parsedValue = value, //(typeof value === "number") ? value : this.parse(value),
                text = this.enabled ? this.text : '',
                isNull = value === null;

      //if (parsedValue != null) 
      //{
      //  parsedValue = parseFloat(parsedValue.toFixed(this.digits));
      //}

      this.val = parsedValue;
      this.$element.val(parsedValue);  // isNull ? '' : this.formatEdit(parsedValue));
      //this.$text.html(parsedValue);    // isNull ? text : this.format(parsedValue));

      //this.$text.toggleClass('t-state-empty', isNull);
    },

    _hideTextBoxValue: function () {
      var $element = this.$element;
      if (this.enabled) {
        setTimeout(function () { $element.css('color', $element.css('background-color')); });
        if ($.browser.opera) {
          $element.css({ 'color': $element.css('background-color'), 'text-indent': '-4444px' });
        }
      }
      else {
        if (!$.browser.msie) {
          $element.css({ 'color': $element.css('background-color'), 'text-indent': '-4444px' });
        }
        else {
          $element.css({ 'color': $element.css('background-color'), 'letter-spacing': '1000px' });
        }
      }
    },

    _showTextBoxValue: function () {
      var $element = this.$element,
                $text = this.$text;

      if (this.enabled) {
        setTimeout(function () { $element.css({ 'color': $text.css('color'), 'text-indent': '', 'letter-spacing': '' }); });
      }
      else {
        if (!$.browser.msie) {
          $element.css({ 'color': $text.css('background-color'), 'text-indent': '0px' });
        }
        else {
          $element.css({ 'color': $text.css('background-color'), 'letter-spacing': '0px' });
        }
      }
    },

    _onParentFormReset: function () {
      var that = this;
      window.setTimeout(function () { that._value(that.$element.val()); }, 1);
    },

    _clear: function () {
      this.val = "";
      this.$element.val(this.val);
      this._update(this.$element.val())
    },

    clear: function () {
      this._clear();
    },

    selectAndFocus: function () {
      if (this.enabled) {
        var input = this.$element[0];
        setTimeout(function () {
          input.focus();
          if ($.browser.msie) {
            input.select();
          }
          else {
            input.selectionStart = 0;
            input.selectionEnd = input.value.length;
          }
        }, 0);
      }
    },

    enable: function () {
      this.enabled = true;
      this.$element.removeAttr("disabled").css("color", this.enableFontColor);

      this.$wrapper.removeClass('t-state-disabled');

      // Enable olduğu zaman Background-Image devre dışı bırakılıyor...
      this.$wrapper.css('background-image', this.backgroundImage);
      this.$wrapper.css('background-color', this.backgroundActiveColor);

      //this.$wrapper.get(0).style.backgroundImage = this.backgroundImage;
      //this.$wrapper.get(0).style.backgroundColor = this.backgroundActiveColor;

      if (this.showTextDeleteButton) {
        var $button = this.$wrapper.find('.t-hgodeletebutton'),
                  clearTimerProxy = $.proxy(this._clearTimer, this);

        $button.css("background-image", "url('HGO.axd?file=text_delete_icon.png')");
        $button.unbind('mouseup').unbind('mouseout').unbind('dblclick')
                      .bind({
                        mouseup: clearTimerProxy,
                        mouseout: clearTimerProxy,
                        dblclick: clearTimerProxy
                      });

        var eventName = "mousedown";
        $button.eq(0)
                      .unbind(eventName)
                      .bind(eventName, $.proxy(function (e) {
                        this._clear();
                        this.$element.focus();
                      }, this));
      }
    },

    disable: function () {
      this.enabled = false;
      this.$element.attr('disabled', 'disabled').css("color", this.disableFontColor);
      this.$wrapper.addClass('t-state-disabled');

      // Disable olduğu zaman Background-Image devre dışı bırakılıyor...
      this.$wrapper.css('background-image', this.backgroundImageEmpty);
      this.$wrapper.css('background-color', this.backgroundPassiveColor);

      //this.$wrapper.get(0).style.backgroundImage = this.backgroundImageEmpty;
      //this.$wrapper.get(0).style.backgroundColor = this.backgroundPassiveColor;

      if (this.showTextDeleteButton) {
        this.$wrapper.find('.t-icon')
                    .unbind('mousedown')
                    .bind('mousedown', $t.preventDefault)
                    .css("background-image", "url('HGO.axd?file=text_delete_icon_disabled.png')");
      }
    },

    value: function (value) {
      if (value === undefined) {
        return this.element.value;
      }

      var parsedValue = value;
      this._value(parsedValue);
    },

    height: function (value) {
      if (value === undefined) {
        return this.$wrapper.height();
      }

      this.$wrapper.height(value);
    }
  }

  $.fn.tHGOTextBox = function (options) {
    var type = 'hgotextbox';
    var defaults = $.fn.tHGOTextBox.defaults[type];
    options = $.extend({}, defaults, options);
    options.type = type;

    return this.each(
                      function () {
                        var $element = $(this);
                        options = $.meta ? $.extend({}, options, $element.data()) : options;

                        if (!$element.data('tHGOTextBox')) {
                          $element.data('tHGOTextBox', new $t.hgotextbox(this, options));
                          $t.trigger(this, 'load');
                        }
                      }
                    );
  };

  var commonDefaults =
  {
    val: null,
    text: '',
    inputAttributes: '',
    textDeleteButtonTitle: "Clear Input Value",
    showTextDeleteButton: true,
    heightMin: 16,
    disableFontColor: "#000000",
    enableFontColor: "black",
    backgroundImage: 'url("HGO.axd?file=ui-button-bg.png") !important',
    backgroundImageEmpty: 'none !important',
    backgroundPassiveColor: '#EAEAEA',
    backgroundActiveColor: 'transparent'
  };

  $.fn.tHGOTextBox.defaults = {
    hgotextbox: $.extend(commonDefaults,
                                      {
                                        prop1: ''
                                      }
                        )
  };

  function currentSelection(element) {
    var selectionStart = -1,
            selectionEnd = -1;

    if (document.selection) {
      var selectedText = element.document.selection.createRange().text,
                length = selectedText.length;

      if (length > 0) {
        selectionStart = element.value.indexOf(selectedText);
        selectionEnd = length;
      }
    }
    else if (element.selectionStart !== undefined) {
      var selStart = element.selectionStart,
                selEnd = element.selectionEnd;
      if (selStart != selEnd) {
        selectionStart = selStart;
        selectionEnd = selEnd;
      }
    }

    return { start: selectionStart, end: selectionEnd };
  };

})(jQuery);

//////////////////// HGO TextBox End Code //////////////////////////////
////////////////////////////////////////////////////////////////////////
///  Örn Disable => $('#HGOTextBox').data('tHGOTextBox').disable() ////
///  Örn Enable => $('#HGOTextBox').data('tHGOTextBox').enable() ////
///  Örn selectAndFocus => $('#HGOTextBox').data('tHGOTextBox').selectAndFocus() ////
///  Örn Focus => $('#HGOTextBox').data('tHGOTextBox').focus() ////
////////////////////////////////////////////////////////////////////////

